const $ = require('jquery')

function Vipspa() {}

Vipspa.prototype.start = function(config) {
    var self = this;
    self.routerMap = config.router;
    self.mainView = config.view;
    self.errorTemplateId = config.errorTemplateId;
    startRouter.call(self);
    window.onhashchange = function() {
        startRouter.call(self);
    };
};

var messageStack = [];

Vipspa.prototype.next = function(path) {
    startRouter.call(this, path);
    return this;
};

Vipspa.prototype.getMessage = function(id) {
    var msg = {};
    $.each(messageStack, function(i, e) {
        if (e.id === id) {
            msg = e;
        }
    });
    return msg;
};

Vipspa.prototype.setMessage = function(obj) {
    var _obj = JSON.parse(JSON.stringify(obj));
    $.each(messageStack, function(i, e) {
        if (e.id === _obj.id) {
            e = _obj;
            return false;
        }
    });
    messageStack.push(_obj);
};
Vipspa.prototype.delMessage = function(id) {
    if (typeof id === 'undefined') {
        return false;
    }
    var index = 0;
    $.each(messageStack, function(i, e) {
        if (e.id === id) {
            index = i;
        }
    });
    $.each(messageStack, function(i, e) {
        if (i > index) {
            messageStack[i - 1] = e;
        }
    });
};
Vipspa.prototype.clearMessage = function(id) {
    var index = 0;
    messageStack = [];
};

Vipspa.prototype.stringify = function(routerUrl, paramObj) {
    var paramStr = '',
        hash;
    for (var i in paramObj) {
        paramStr += i + '=' + encodeURIComponent(paramObj[i]) + '&';
    }
    if (paramStr === '') {
        hash = routerUrl;
    } else {
        paramStr = paramStr.substring(0, paramStr.length - 1);
        hash = routerUrl + '?' + paramStr;
    }
    return hash;
};

Vipspa.prototype.parse = function(routerHash) {
    var hash = typeof routerHash === 'undefined' ? location.hash : routerHash;
    var obj = {
        url: '',
        param: {}
    };
    var param = {},
        url = '';
    var pIndex = hash.indexOf('?');
    if (hash === '') {
        return obj;
    }

    if (pIndex > -1) {
        url = hash.substring(1, pIndex);
        var paramStr = hash.substring(pIndex + 1);
        var paramArr = paramStr.split('&');

        $.each(paramArr, function(i, e) {
            var item = e.split('='),
                key,
                val;
            key = item[0];
            val = item[1];
            if (key !== '') {
                param[key] = decodeURIComponent(val);
            }

        });
    } else {
        url = hash.substring(1);
        param = {};
    }
    return {
        url: url,
        param: param
    };
};

function routerAction(routeObj, path) {
    var routerItem = this.routerMap[path || routeObj.url];
    if (typeof routerItem === 'undefined') {
        var defaultsRoute = this.routerMap.defaults;
        routerItem = this.routerMap[defaultsRoute];
        location.hash = defaultsRoute;
        return false;
    }

    if (!routerItem.component)
        return
    // routerItem.component
    let {
        page,
        init,
    } = routerItem.component;

    $('body>div').each(function(idx, ele) {
        if (ele.id != 'app')
            $(ele).remove()
    })

    if (typeof page == 'function') {
        page((data) => {
            $(this.mainView).html(data && data.default || data);
            if (typeof init == 'function')
                init()
        })
    }
    if (typeof page == 'string') {
        $(this.mainView).html(page);
        if (typeof init == 'function')
            setTimeout(init, 50)
    }
}

function startRouter(path) {
    let hash = path || location.hash;
    location.hash = hash
    let routeObj = this.parse(hash);
    routerAction.call(this, routeObj, path);
}

module.exports = new Vipspa